<script context="module">
  export async function preload(page, session) {
    if (!session.user) {
      this.error(403, "对不起，请登录之后再使用发布功能！");
      return;
    }
  }
</script>

<script>
  let type = "in";
  let amount = 0;
  let description = "";
  let disabled = false;
  let error;
  let value;
  let exchanges = [];
  const optionIdentifier = "_id";
  const getOptionLabel = (option) => option.title;
  const getSelectionLabel = (option) => option.title;
  const items = [{ _id: "1", title: "油漆一", pid: "jjjjee" }];
  import { stores, goto } from "@sapper/app";
  import Select from "svelte-select/src";
  import item from "../../components/ProductItem.svelte";
  function handleSelect(event) {
    console.log("selected item", event.detail);
    // .. do something here 🙂
    exchanges = [...exchanges, event.detail];
  }
  function deleteExchange(id) {
    exchanges = exchanges.filter((m) => m._id !== id);
  }
  async function loadOptions(filterText) {
    const response = await fetch("/api2/product?q=" + filterText, {
      method: "get",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
    }).catch((err) => {
      console.log(err);
    });
    const parsed = await response.json();
    return parsed.products;
  }
  const post = async () => {
    if (type.length == 0) {
      error = "商品分类名称为必填项！";
      return;
    }
    if (amount == 0) {
      error = "金额不能为0";
      return;
    }
    disabled = true;
    const response = await fetch("/api2/cash", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
      body: JSON.stringify({
        type,
        amount,
        description,
        exchanges: exchanges.map(x => { return { product: x._id, counts: x.counts } })
      }),
    }).catch((err) => {
      console.log(err);
      disabled = false;
    });
    disabled = false;
    const parsed = await response.json();
    if (parsed.success == 0) {
      error = parsed.message;
    } else if (parsed.success == 1) {
      await goto("/cash");
    }
  };
</script>

<svelte:head>
  <title>新增支出或收入</title>
</svelte:head>
<div class="panel-header panel-header-sm" />
<div class="content">
  <div class="row">
    <div class="col-md-4 order-md-1 mb-4">
      <div class="card shadow">
        <div class="card-header">
          <h5 class="type">提示</h5>
        </div>
        <div class="card-body">
          <p>一、分为支出或收入。</p>
          <p>二、选择了交易商品，并且设置了交易数量之后并不会对库存数产生变化，请自行处理库存！</p>
          <p>三、选择交易商品之后，会默认显示库存数，请修改成<strong>本次交易数量</strong>！</p>
          <p>四、备注可不填！</p>
        </div>
      </div>
    </div>
    <div class="col-md-8 mx-auto">
      <div class="card shadow">
        <div class="card-header">
          <h5 class="type">新增支付或收入</h5>
        </div>
        <div class="card-body">
          <form on:submit|preventDefault={post} action="post">
            <div class="form-group row">
              <label class="col-sm-2 col-form-label" for="type">类型</label>
              <div class="col-sm-10">
                <div>
                  <label class="checkbox-inline m-2" style="color:red">
                    <input
                      class="types"
                      type="radio"
                      value="in"
                      bind:group={type}
                    />
                    <i class="fas fa-chevron-circle-up" /> 收入
                  </label>
                  <label class="checkbox-inline m-2" style="color:green">
                    <input
                      class="types"
                      type="radio"
                      value="out"
                      bind:group={type}
                    />
                    <i class="fas fa-chevron-circle-down" /> 支出
                  </label>
                </div>
              </div>
            </div>
            <div class="form-group row">
              <label class="col-sm-2 col-form-label" for="amount">金额数</label>
              <div class="col-sm-10">
                <input
                  type="number"
                  step="0.01"
                  id="amount"
                  class="form-control"
                  placeholder="输入交易金额数"
                  bind:value={amount}
                />
              </div>
            </div>
            <div class="form-group row">
              <label class="col-sm-2 col-form-label" for="amount"
                >交易商品</label
              >
              <div class="col-sm-10">
                <Select
                  {loadOptions}
                  {value}
                  {optionIdentifier}
                  {getSelectionLabel}
                  {getOptionLabel}
                  Item={item}
                  on:select={handleSelect}
                  placeholder="关键词或编号搜索并添加"
                />
                <div class="form-control mt-2" style="min-height:100px;height:auto;max-height:400px;overflow-y:auto;">
                  {#if exchanges.length == 0}
                    暂无商品
                  {:else}
                    <ul class="list-group">
                      {#each exchanges as exchange}
                        <li
                          class="list-group-item d-flex justify-content-between align-items-center"
                        >
                          <div>
                            {exchange.title}
                            <small class="text-muted"
                              >编号：{exchange.pid}</small
                            >
                          </div>
                          <div>
                            <input
                              style="padding: .375rem .75rem;"
                              class="bg-light"
                              placeholder="输入交易数量"
                              type="number"
                              bind:value={exchange.counts}
                            />
                          </div>
                          <div>
                            <svg
                              on:click={() => {
                                deleteExchange(exchange._id);
                              }}
                              style="height:15px"
                              width="100%"
                              height="100%"
                              viewBox="-2 -2 50 50"
                              focusable="false"
                              aria-hidden="true"
                              role="presentation"
                              ><path
                                fill="currentColor"
                                d="M34.923,37.251L24,26.328L13.077,37.251L9.436,33.61l10.923-10.923L9.436,11.765l3.641-3.641L24,19.047L34.923,8.124
                            l3.641,3.641L27.641,22.688L38.564,33.61L34.923,37.251z"
                              /></svg
                            >
                          </div>
                        </li>
                      {/each}
                    </ul>
                  {/if}
                </div>
              </div>
            </div>
            <div class="form-group row">
              <label class="col-sm-2 col-form-label" for="description"
                >交易备注</label
              >
              <div class="col-sm-10">
                <textarea
                  id="description"
                  class="form-control"
                  rows="6"
                  placeholder="输入备注，可不填"
                  bind:value={description}
                />
              </div>
            </div>
            <div class="form-group">
              <button type="submit" class="btn btn-primary" {disabled}
                >提交新增</button
              >
            </div>
          </form>
          {#if error}
            <div class="row">
              <div class="col-md-12">
                <p class="text-danger">{error}</p>
              </div>
            </div>
          {/if}
        </div>
      </div>
    </div>
  </div>
</div>
